
from flask import Blueprint,request,jsonify,g
from modle import *
from flask_restful import Api,Resource,marshal,reqparse
import time,modle
from time import time
user_bp=Blueprint("user",__name__,url_prefix='/user')

@user_bp.route('/login',methods=['post'])
def grt():
    data=request.json
    if not data:
        return {'smg':'字段不完整'}
    name=data.get('name')
    mobile=data.get('mobile')
    password=data.get('password')
    img=data.get('img')
    money=data.get('money')
    if not all([mobile,name,password,img,money]):
        return jsonify({'code': 400, 'msg': '参数错误'})
    u=User(name=name,mobile=mobile,password=password,img=img,money=money)
    db.session.add(u)
    db.session.commit()
    return jsonify({'code':200,'msg':'登陆成功'})

@user_bp.route("/oo",methods=["post"])
def gre():
    data=request.json
    if not data:
        return {'smg': '字段不完整'}
    cname=data.get('cname')
    shops_id=data.get('shops_id')
    if not all([cname,shops_id]):
        return jsonify({"msg":'参数错误'})
    cate=Cate(cname=cname,shops_id=shops_id)
    db.session.add(cate)
    db.session.commit()
    return jsonify({'code':200,'msg':'添加成功'})

@user_bp.route('/pp',methods=['post'])
def gty():
    data=request.json
    if not data:
        return {"msg":'不完整'}
    address=data.get('address')
    state=data.get('state')
    price=data.get('price')
    number=data.get('number')
    remark=data.get('remark')
    user_id=data.get('user_id')
    if not all([address,state,price,number,remark,user_id]):
        return jsonify({'msg':'参数错误'})
    f=Order(address=address,state=state,price=price,number=number,remark=remark,user_id=user_id)
    db.session.add(f)
    db.session.commit()
    return jsonify({'code':200,'msg':'成功'})

@user_bp.route("/yy",methods=['post'])
def ieg():
    data=request.json
    if not data:
        return {"msg":"字段不完整"}
    price=data.get("price")
    number=data.get("number")
    user_id=data.get("user_id")
    product_id=data.get("product_id")
    if not all([price,number,user_id,product_id]):
        return jsonify({"msg":'参数错误'})
    b=Shoping(price=price,number=number,user_id=user_id,product_id=product_id)
    db.session.add(b)
    db.session.commit()
    return jsonify({'code': 200, 'msg': '成功'})

@user_bp.route('/shop',methods=['POST'])
def shop():
    data=request.json
    sh_name = data.get('sh_name')
    price = data.get('price')
    repertory = data.get('repertory')
    img = data.get('img')
    referral = data.get('referral')
    cate_id = data.get('cate_id')
    shops_id = data.get('shops_id')

    shop=Shop(sh_name = sh_name,price = price,repertory = repertory,img = img,referral=referral,cate_id =cate_id,shops_id = shops_id)
    db.session.add(shop)
    db.session.commit()
    return jsonify({'code':200,'msg':'添加成功'})

@user_bp.route('/ww',methods=['post'])
def ghj():
    data=request.json
    if not data:
        return {"msg": "字段不完整"}
    shop_id = data.get("shop_id")
    mate_id = data.get("mate_id")
    order_id = data.get("order_id")
    if not all([order_id, shop_id, mate_id]):
        return jsonify({"msg": '参数错误'})
    o = product(shop_id=shop_id, mate_id=mate_id, order_id=order_id)
    db.session.add(o)
    db.session.commit()
    return jsonify({'code': 200, 'msg': '成功'})

@user_bp.route('/rr',methods=['post'])
def ghp():
    data=request.json
    if not data:
        return {"msg": "字段不完整"}
    mate_name = data.get("mate_name")
    price = data.get("price")
    if not all([ mate_name, price]):
        return jsonify({"msg": '参数错误'})
    q= Material(mate_name=mate_name,price=price)
    db.session.add(q)
    db.session.commit()
    return jsonify({'code': 200, 'msg': '成功'})

@user_bp.route('/ss',methods=['post'])
def ghw():
    data=request.json
    if not data:
        return {"msg": "字段不完整"}
    shops_name = data.get("mate_name")
    address = data.get("address")
    state = data.get("state")
    mobile = data.get("mobile")
    if not all([shops_name,address,state,mobile]):
        return jsonify({"msg": '参数错误'})
    eo = Shops(shops_nam=shops_name,address=address,state=state,mobile=mobile)
    db.session.add(eo)
    db.session.commit()
    return jsonify({'code': 200, 'msg': '成功'})

@user_bp.route('/yh',methods=['get'])
def cvc():
    data=User.query.all()
    list=[{
        'id':i.id,
        'name':i.name,
        'mobile':i.mobile,
        'password':i.password,
        'img':i.img,
        'money':i.money
    }for i in data]
    return jsonify({'code':200,'msg':'展示成功','data':list})

@user_bp.route('/lx',methods=['get'])
def cvc1():
    data=Cate.query.all()
    list=[{
        'id':i.id,
        'cname':i.cname,
        'shops_id':i.shops_id,
    }for i in data]
    return jsonify({'code':200,'msg':'展示成功','data':list})


@user_bp.route('/dd',methods=['get'])
def cvc2():
    data=Order.query.all()
    list=[{
        'id':i.id,
        'address':i.address,
        'state': i.state,
        'price':i.price,
        'number':i.number,
        'remark':i.remark,
        'user_id':i.user_id,
    }for i in data]
    return jsonify({'code':200,'msg':'展示成功','data':list})

@user_bp.route('/gu',methods=['get'])
def cvc3():
    data=Shoping.query.all()
    list=[{
        "id":i.id,
        'price':i.price,
        'number':i.number,
        'user_id':i.user_id,
        'product_id':i.product_id
    }for i in data]
    return jsonify({'code': 200, 'msg': '展示成功', 'data': list})

@user_bp.route('/sp',methods=['get'])
def cvc4():
    data=Shop.query.all()
    list=[{
        "id":i.id,
        'sh_name':i.sh_name,
        'price':i.price,
        'repertory':i.repertory,
        'img':i.img,
        'referral':i.referral,
        'cate_id':i.cate_id,
        'shops_id':i.shops_id
    }for i in data]
    return jsonify({'code': 200, 'msg': '展示成功', 'data': list})

@user_bp.route('/cp',methods=['get'])
def cvc5():
    data=product.query.all()
    list=[{
        "id":i.id,
        'shop_id':i.shop_id,
        'mate_id':i.mate_id,
        'order_id':i.order_id,
    }for i in data]
    return jsonify({'code': 200, 'msg': '展示成功', 'data': list})

@user_bp.route('/xl',methods=['get'])
def cvc6():
    data=Material.query.all()
    list=[{
        "id":i.id,
        'mate_name':i.mate_name,
        'price':i.price,
    }for i in data]
    return jsonify({'code': 200, 'msg': '展示成功', 'data': list})


@user_bp.route('/sj',methods=['get'])
def cvc7():
    data=Shops.query.all()
    list=[{
        "id":i.id,
        'shops_name':i.shops_name,
        'state':i.state,
        'mobile':i.mobile,
    }for i in data]
    return jsonify({'code': 200, 'msg': '展示成功', 'data': list})


@user_bp.after_request
def add_log(response):
    try:
        uid=response.args.get('uid') or g.get('uid')
        if not uid:
            return KeyError
    except KeyError as e:
        print(request.url)
        return response
    pass

@user_bp.route('/small',methods=['get'])
def user_small():
    name=request.args.get('name')
    goods=User.query.filter_by(name=name).first()
    small=goods.small
    small_list=[{
        'id':i.id,
        'name':i.name
    }for i in small]
    return small_list

@user_bp.route('/shop',methods=['post'])
def shop_add_good():
    uid=request.args.get('uid')
    business=Shop.query.get(user_id=uid)
    business_lst=[{
        'id':i.id,
        'name':i.name,
        'addr':i.addr,
        'open':i.open,
        'tel':i.tel
    }for i in business]
    return {'msg':'ok','data':business_lst}

@user_bp.route('/Business',methods=['get'])
def user_business():
    business=Shops.query.all()
    business_lst=[{
        'id':i.id,
        'name':i.name,
        'addr':i.addr,
        'open':i.open,
        'tel':i.tel
    } for i in business]
    return {'msg':'ok','data':business_lst}


@user_bp.route('/log',methods=['post'])
def user_login():
    global power_lst
    name=request.form.get('name')
    password=request.form.get('password')
    if not all([name,password]):
        return {'msg':'字段不完整','code':400}
    if not User.query.filter_by(naem=name).first():
        return {'msg':'用户不存在','code':400}
    user=User.query.filter_by(password=password).first()
    if user.passwprd !=password:
        return '密码错误'
    roles=user.role_id
    role_lst=[]
    power_dict={}
    for i in roles:
        power=i.power
        role_lst.append({'name':i.name,'power':i.power})
        for v in power:
            power_dict[v.id]=v
            power_lst=[Role(1)for i in power_dict.values()]
            power_role=[{
                'name':i['name'],
                'url':i['url'],
                'method':i['method']
            }for i in power_lst]
            return {'msg': "登陆成功",'data':{
                    'power':power_role,
                    'uname' : user .name,
            }}
        # power=sum([roles.power for role in user.role_id],[])
        # return {'name':user.name,'power':{itme.get('id'):itme for item in item2dict(power)}}
@user_bp.route('/zz',methods=['put'])
def jkk1():
    good = request.json
    g_id=good.pop('id')
    Shop.query.filter_by(id=g_id).update(good)
    db.session.commit()
    return {"msg":'修改成功','code':200,'data':good}

@user_bp.route('/zx',methods=['put'])
def jkk2():
    good = request.json
    g_id=good.pop('id')
    Shops.query.filter_by(id=g_id).update(good)
    db.session.commit()
    return {"msg":'修改成功','code':200,'data':good}

@user_bp.route('/zc',methods=['put'])
def jkk3():
    good = request.json
    g_id=good.pop('id')
    Cate.query.filter_by(id=g_id).update(good)
    db.session.commit()
    return {"msg":'修改成功','code':200,'data':good}

@user_bp.route('/zv',methods=['put'])
def jkk4():
    good = request.json
    g_id=good.pop('id')
    Order.query.filter_by(id=g_id).update(good)
    db.session.commit()
    return {"msg":'修改成功','code':200,'data':good}

@user_bp.route('/zb',methods=['put'])
def jkk5():
    good = request.json
    g_id=good.pop('id')
    Shoping.query.filter_by(id=g_id).update(good)
    db.session.commit()
    return {"msg":'修改成功','code':200,'data':good}

@user_bp.route('/zn',methods=['put'])
def jkk6():
    good = request.json
    g_id=good.pop('id')
    product.query.filter_by(id=g_id).update(good)
    db.session.commit()
    return {"msg":'修改成功','code':200,'data':good}

@user_bp.route('/zm',methods=['put'])
def jkk7():
    good = request.json
    g_id=good.pop('id')
    Material.query.filter_by(id=g_id).update(good)
    db.session.commit()
    return {"msg":'修改成功','code':200,'data':good}

# @user_bp.route('/<table_name>',methods=['put'])
# def ii(table_name):
#     table=table_name.title()
#     good=request.json
#     g_id=good.pop('id')
#     if hasattr(modle,table):
#         getattr(modle,table).query.filter_by(id=g_id).updata(good)
#     else:
#         return {'code':404,'msg':'错误','data':good}
#     db.session.commit()
#     return {'code':200,'msg':'修改成功','data':good}

@user_bp.route('/orute',methods=['post'])
def shop2ood():
    uid=request.args.get('uid')
    shops=Shop.query.filter_by(id=uid).all()
    order=Order()
    order.finish.extend([i.finish[0]for i in shops]) 3
    nums={i.finish[0].good_id:i.num for i in shops}
    db.session.query(goods_business)\
        .filter(goods_business.c.good_id.in_(nums))\
        .filter(goods_business.c.num !=None)\
        .update({goods_business.c.num:goods_business.c.num - nums[1]},
                synchronize_session="evaluate"),

    db.session.add(order)
    db.session.commit()